#include "xmlhelper.h"

int xmlh_get_xform(mat4_t xform, struct xml_node *node)
{
	int i;
	vec3_t pos = {0, 0, 0}, scale = {1, 1, 1}, pivot = {0, 0, 0};
	quat_t rot = {0, 0, 0, 1};
	mat4_t mat_prs, mat_xform;
	struct xml_attr *attr;

	if((attr = xml_get_attr(node, "pos"))) {
		pos = v3_cons(attr->vval[0], attr->vval[1], attr->vval[2]);
	}
	if((attr = xml_get_attr(node, "rot"))) {
		rot = quat_cons(attr->vval[0], attr->vval[1], attr->vval[2], attr->vval[3]);
	}
	if((attr = xml_get_attr(node, "scale"))) {
		scale = v3_cons(attr->vval[0], attr->vval[1], attr->vval[2]);
	}
	if((attr = xml_get_attr(node, "pivot"))) {
		pivot = v3_cons(attr->vval[0], attr->vval[1], attr->vval[2]);
	}

	/* construct PRS matrix */
	m4_identity(mat_prs);
	m4_translate(mat_prs, pivot.x, pivot.y, pivot.z);
	m4_translate(mat_prs, pos.x, pos.y, pos.z);
	m4_rotate_quat(mat_prs, rot);
	m4_scale(mat_prs, scale.x, scale.y, scale.z);
	m4_translate(mat_prs, -pivot.x, -pivot.y, -pivot.z);

	/* read raw matrix, if present */
	m4_identity(mat_xform);
	for(i=0; i<4; i++) {
		char name[] = "mat_rowX";

		name[7] = '0' + i;
		if((attr = xml_get_attr(node, name))) {
			memcpy(&mat_xform[i][0], attr->vval, 4 * sizeof *attr->vval);
		}
	}

	/* combine the two and calculate the inverse */
	m4_mult(xform, mat_prs, mat_xform);
	return 0;
}
